package com.bprogram.controller;


import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.bprogram.pojo.User;
import com.bprogram.pojo.Video;
import com.bprogram.service.VideoService;
import com.bprogram.utils.RedisUtil;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.util.Assert;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author cai
 * @since 2023-11-21
 */
@RestController
@RequestMapping("/video")
public class VideoController {


    @Autowired
    private VideoService videoService;
    @Resource
    private UploadFeign uploadFeign;

    @Resource
    private RedisUtil redisUtil;

    @Autowired
    private CommentFeign commentFeign;
    @Autowired
    private UserFeign userFeign;


    @PostMapping("/saveOrUpdateVideo")
    public Video saveOrUpdate(@RequestBody Video video) {
        //判断是否有上传有视频和封面
        if (StringUtils.isEmpty(video.getUploadId())) {
            Assert.isTrue(false, "请先上传视频在投稿");
        } else if (StringUtils.isEmpty(video.getVideoCoverId())) {
            Assert.isTrue(false, "请先上传视频封面后在投稿");
        }
        return videoService.saveOrUpdateVideo(video);
    }

    @GetMapping("/getVideo")
    public Video getVideo(long id) {
        //自增1播放量
        likeForVideo(id, "videoPlayTimes");

        //获取存在redis中该视频的数据
        String videoPlayTimes = redisUtil.hget(id + "", "videoPlayTimes") + "";
        String videoForward = redisUtil.hget(id + "", "videoForward") + "";
        String videoComments = commentFeign.getCounts(id) + "";
        String videoLike = redisUtil.hget(id + "", "videoLike") + "";
        String videoCollects = redisUtil.hget(id + "", "videoCollects") + "";
        Video video = videoService.getById(id);
        video.setVideoComments(videoComments)
                .setVideoCollects(videoCollects).setVideoLike(videoLike).setVideoForward(videoForward).setVideoPlayTimes(videoPlayTimes);


        return video;
    }

    @GetMapping("/deleteVideo")
    public boolean deleteVideo(long id) {
        //删除视频文件，和封面文件
        Video video = getVideo(id);
        uploadFeign.deleteInServer(video.getVideoCover());
        uploadFeign.deleteInServer(video.getVideoPath());
        uploadFeign.deleteInDB(video.getUploadId());
        uploadFeign.deleteInDB(video.getVideoCoverId());
        //删除该视频的评论
        commentFeign.deleteComment(id);
        return videoService.removeById(id);
    }

    @GetMapping("/getAll")
    public List<Video> getAllVideo() {
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        wrapper.select("uploadId", "videoCoverId");
        List<Video> list = videoService.list(wrapper);


        return list;
    }

    /**
     * 分页
     *
     * @param currentPage
     * @param pageSize
     * @param location    发布视频者的id，若传来的是simple：既是当前登录人发出用于查看自己的投稿，
     * @param partId      根据partId模糊查询该视频所属分区
     * @return
     */
    @GetMapping("/getPageVideo")
    public IPage<Video> getPageVideo(String currentPage, String pageSize, String videoTitle, String location, String partId) {
        return videoService.getPageVideo(currentPage, pageSize, videoTitle, location, partId);
    }


    /**
     * 给视频点赞，收藏等操作
     *
     * @param videoId
     * @param type    //操作类型
     */
    @GetMapping("/likeForVideo")
    public void likeForVideo(long videoId, String type) {
        //禁止重复点赞，建立关系---视频和用户，0：两不相关，1：点赞，2收藏，4：转发,3:点赞+收藏。5：点赞+转发，6：收藏+转发，7三联

        //将要把数据需要保存到mysql的videoId存到redis中
        redisUtil.sSet("sanLianVideoData", "" + videoId);
        double incr = 1;
        if ("videoPlayTimes".equals(type)) {
            redisUtil.hincr(videoId + "", "videoPlayTimes", incr);
        }
        if ("videoForward".equals(type)) {
            redisUtil.hincr(videoId + "", "videoForward", incr);
        }
        if ("videoLike".equals(type)) {
            redisUtil.hincr(videoId + "", "videoLike", incr);
        }
//        if ("videoComments".equals(type)) {
//            redisUtil.hincr(videoId + "", "videoComments", incr);
//        }
//        if ("videoCollects".equals(type)) {
//            redisUtil.hincr(videoId + "", "videoCollects", incr);
//        }
    }

    //更新三联数据,每30分钟执行一次
    @Scheduled(cron = "0 0/30 * * * ?")
    //每30秒执行一次测试
//    @Scheduled(cron = "0/30 * * * * ?")

    public void updateSanLianDate() {
        System.out.println("更新三联数据啦");
        Set<Object> videoIds = redisUtil.sGet("sanLianVideoData");
        System.out.println(videoIds.toString());
        for (Object videoId : videoIds) {
            redisUtil.setRemove("sanLianVideoData", videoId);
            String videoPlayTimes = redisUtil.hget(videoId + "", "videoPlayTimes") + "";
            String videoForward = redisUtil.hget(videoId + "", "videoForward") + "";
            String videoLike = redisUtil.hget(videoId + "", "videoLike") + "";
            String videoComments = commentFeign.getCounts(Long.parseLong(videoId + "")) + "";
            Video video = videoService.getById(Long.parseLong(videoId + ""))
.setVideoComments(videoComments)
                    .setVideoPlayTimes(videoPlayTimes)
                    .setVideoForward(videoForward)
                    .setVideoLike(videoLike)
                    .setUpdateId(1738148946666666666l)
                    .setUpdateCode("123456")
                    .setUpdateName("super")
                    .setUpdateTime(LocalDateTime.now())
                    ;

            videoService.updateByVideoId(video);

        }

        System.out.println("更新完毕");
    }


    /**
     * 根据UpId获取到他所有视频的总播放数
     *
     * @param upId
     * @return
     */
    @GetMapping("/getTotalPlayTimesByUpId")
    public String getTotalPlayTimesByUpId(long upId) {
        return videoService.getTotalPlayTimesByUpId(upId);
    }

    /**
     * 根据UpId获取到他所有视频的总点赞数
     *
     * @param upId
     * @return
     */
    @GetMapping("/getTotalLikeByUpId")
    public String getTotalLikeByUpId(long upId) {
        return videoService.getTotalLikeByUpId(upId);
    }

    /**
     * 根据UpId获取到他所有视频的总投稿数
     *
     * @param upId
     * @return
     */
    @GetMapping("/getTotalUploadByUpId")
    public String getTotalUploadByUpId(long upId) {
        return videoService.getTotalUploadByUpId(upId);
    }

    /**
     * 获取所有关注的视频列表
     *
     * @param
     * @return
     */
    @PostMapping("/getVideoListByUpIds")
    public List<Video> getVideoListByUpIds(@RequestBody String upList) {

        List<User> userList = JSON.parseArray(JSON.parseObject(upList).getString("upList"), User.class);
        QueryWrapper<Video> wrapper = new QueryWrapper<>();
        List<Long> upIds = userList.stream().map(User::getUserId).collect(Collectors.toList());
        wrapper.in("upId", upIds);
        List<Video> list = videoService.list(wrapper);
        list.stream().forEach(video -> {
            video.setUploadUser(userFeign.getById(video.getUpId()));
        });
        return list;
    }

}

